package org.shopen.puremvc.view
{
	import flash.events.ErrorEvent;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.puremvc.ApplicationConstants;
	import org.shopen.puremvc.model.TheoryProxy;
	import org.shopen.puremvc.model.domain.theory.Theory;
	import org.shopen.puremvc.model.domain.theory.TheoryMeta;
	import org.shopen.puremvc.view.components.theory.ContentItem;

	public class ContentItemMediator extends Mediator
	{
		public static const NAME : String = "ContentItemMediator";
		
		[Bindable]
		public var meta : TheoryMeta;
				
		protected function get contentItem() : ContentItem
		{
			var result : ContentItem = viewComponent as ContentItem;
			return result;
		}
		
		public function ContentItemMediator(viewComponent:Object, meta:TheoryMeta)
		{
			super(ContentItemMediator.NAME+meta.id, viewComponent);
			this.meta = meta;
		}
		
		override public function getMediatorName():String
		{
			return ContentItemMediator.NAME + meta.id;
		}
		
		override public function onRegister() : void
		{
			contentItem.addEventListener(ErrorEvent.ERROR, errorListener);
		}
		
		protected function loadPage() : void
		{
			sendNotification(ApplicationConstants.LOAD_THEORY, meta, meta.id);
		}
		
		override public function listNotificationInterests():Array
		{
			return [ApplicationConstants.INIT_THEORY,
					TheoryProxy.THEORY_PAGE_LOADED,
					TheoryProxy.THEORY_PAGE_LOAD_FAILED];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			try
			{
				var noteName : String = notification.getName();
				
				// have no business with strange notifications
				var noteType : String = notification.getType();
				if (noteType != meta.id)
				{
					return;
				}
				
				switch (noteName)
				{
					case TheoryProxy.THEORY_PAGE_LOADED:
						var theory : Theory = notification.getBody() as Theory;
						contentItem.styleSheet = theory.styleSheet;
						contentItem.htmlText = theory.htmlText;
						contentItem.titleText = theory.meta.title;
						break;
					case TheoryProxy.THEORY_PAGE_LOAD_FAILED:
						contentItem.htmlText = "<p align='center'><font color='#FF0000' size='20'>Не вдалось завантажити сторінку.</font></p>";
						contentItem.titleText = "Без назви";
						//sendNotification(ApplicationConstants.GENERAL_ERROR, notification.getBody(), notification.getType());
						break;
					case ApplicationConstants.INIT_THEORY:
						loadPage();
						break;
				}
			}
			catch(error : Error)
			{
				sendNotification(ApplicationConstants.GENERAL_ERROR, error);
			}
		}
		
		private function errorListener(error : ErrorEvent) :void
		{
			sendNotification(ApplicationConstants.GENERAL_ERROR, "Трапилась помилка підчас завантаження даних із сторінки!");
		}
	}
}